import {useEffect,useReducer} from "react"
import axios from 'axios';

const reducer = (state:any,action:any) => {
    switch (action.type) {
        case "axios/success":
            return  {
                isLoading: false,
                isErroy:false,
                data:action.payload
            }
        case "axios/eorry":
            return  {
                isLoading: false,
                isErroy:true,
                data:null
            }
        case "axios/loading":
            return  {
                isLoading: true,
                isErroy:false,
                data:null
            }
        default :
            throw new Error()
       
    }
}
const useData = (url:string) =>{
    const [state,dispatch] = useReducer(reducer,{
        isLoading: false,
        isErroy:false,
        data:null
    })

    useEffect(() => {
        const get_data = async () =>{
            dispatch({type:"axios/loading"})
            try {
                const result = await axios.get(url)
                dispatch({type:"axios/success",payload:result.data})
            } catch (e){
                dispatch({type:"axios/error"})
            }
        }
        get_data()
    },[])
    return state
}

export default useData